<!-- src/views/operations/index.vue -->
<script setup>
import { ref, onMounted } from 'vue'
import { getOperationsPageApi, confirmOperationsApi, changeOperationsApi, deleteOperationsApi, getOperationsDetailApi } from '@/api/operations/operations.js'
import { getUserListApi } from '@/api/user.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import ProcessingDialog from './ProcessingDialog.vue'

// 状态选项
const statusOptions = [
  { label: '未确认', value: 1 },
  { label: '已确认', value: 2 },
  { label: '已调整', value: 3 }
]

// 作业类型选项
const categoryOptions = [
  { label: '拆分加工', value: 1 },
  { label: '组合加工', value: 2 }
]

// 搜索表单
const searchForm = ref({
  jobCode: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 用户列表
const userList = ref([])

// 加工处理弹窗引用
const processingDialogRef = ref(null)

// 获取作业列表
const fetchOperationsList = async () => {
  loading.value = true
  try {
    const res = await getOperationsPageApi(
      pagination.value.page,
      pagination.value.pageSize,
      searchForm.value.jobCode
    )
    tableData.value = res.data.rows
    pagination.value.total = res.data.total
  } catch (error) {
    ElMessage.error('获取作业列表失败')
  } finally {
    loading.value = false
  }
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    const res = await getUserListApi()
    userList.value = res.data
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  }
}

// 获取用户名
const getUserName = (userId) => {
  const user = userList.value.find(item => item.id == userId)
  return user ? user.name : '未知用户'
}

// 获取状态标签
const getStatusLabel = (status) => {
  const statusMap = {
    1: '未确认',
    2: '已确认',
    3: '已调整'
  }
  return statusMap[status] || '未知状态'
}

// 获取作业类型标签
const getCategoryLabel = (category) => {
  const categoryMap = {
    1: '拆分加工',
    2: '组合加工'
  }
  return categoryMap[category] || '未知类型'
}

// 处理搜索
const handleSearch = () => {
  pagination.value.page = 1
  fetchOperationsList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    jobCode: ''
  }
  pagination.value.page = 1
  fetchOperationsList()
}

// 分页变化
const handlePageChange = (page) => {
  pagination.value.page = page
  fetchOperationsList()
}

// 拆分加工按钮点击事件
const handleSplitProcessing = () => {
  // 通过ref调用ProcessingDialog的open方法
  processingDialogRef.value.open({
    title: '拆分加工',
  })
}

// 组合加工按钮点击事件
const handleCombineProcessing = () => {
  // 通过ref调用ProcessingDialog的open方法
  processingDialogRef.value.open({
    title: '组合加工',
  })
}

// 查看详情
const handleViewDetails = async (id) => {
  try {
    const res = await getOperationsDetailApi(id)
    if (res.code === 1) {
      // 处理数据，根据category分类
      const sourceData = []
      const targetData = []
      
      res.data.forEach(item => {
        const product = {
          id: item.id,
          skuId: item.skuId,
          code: item.code,
          title: item.title,
          name: item.title,
          count: item.count,
          warehouseAreaLocaName: item.warehouseAreaLocaName,
          // 根据category判断是来源还是目标
          ...(item.category === 1 ? {
            originalCount: item.count
          } : {
            targetCount: item.count,
            targetLocation: item.warehouseAreaLocaName
          })
        }
        
        if (item.category === 1) {
          sourceData.push(product)
        } else {
          targetData.push(product)
        }
      })
      
      // 确定操作类型标题
      let title = '加工详情'
      if (sourceData.length > 0 && targetData.length > 0) {
        // 根据数据判断是拆分还是组合
        title = sourceData.length === 1 && targetData.length > 1 ? '拆分加工详情' : '组合加工详情'
      } else if (sourceData.length > 0) {
        title = '拆分加工详情'
      } else if (targetData.length > 0) {
        title = '组合加工详情'
      }
      
      // 打开ProcessingDialog显示详情
      processingDialogRef.value.open({
        title: title,
        sourceData: sourceData,
        targetData: targetData,
        readonly: true // 添加只读标志
      })
    } else {
      ElMessage.error(res.msg || '获取详情失败')
    }
  } catch (error) {
    ElMessage.error('获取详情失败: ' + error.message)
  }
}

// 确认操作
const handleConfirm = (id) => {
  ElMessageBox.confirm('确认要执行此操作吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await confirmOperationsApi(id)
      if (res.code === 1) {
        ElMessage.success('确认成功')
        fetchOperationsList()
      } else {
        ElMessage.error(res.msg || '确认失败')
      }
    } catch (error) {
      ElMessage.error('确认失败: ' + error.message)
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 调整操作
const handleChange = (id) => {
  ElMessageBox.confirm('确认要执行此操作吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await changeOperationsApi(id)
      if (res.code === 1) {
        ElMessage.success('调整成功')
        fetchOperationsList()
      } else {
        ElMessage.error(res.msg || '调整失败')
      }
    } catch (error) {
      ElMessage.error('调整失败: ' + error.message)
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 删除操作
const handleDelete = (id) => {
  ElMessageBox.confirm('确认要删除此记录吗？此操作不可恢复', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    try {
      const res = await deleteOperationsApi(id)
      if (res.code === 1) {
        ElMessage.success('删除成功')
        fetchOperationsList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 初始化
onMounted(() => {
  fetchOperationsList()
  fetchUserList()
})
</script>

<template>
  <div class="operations-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <!-- 左侧按钮 -->
        <div class="left-section">
          <el-button type="primary" class="action-btn" @click="handleSplitProcessing">
            <i class="el-icon-circle-plus"></i> 拆分加工
          </el-button>
          <el-button type="primary" class="action-btn" @click="handleCombineProcessing">
            <i class="el-icon-circle-plus"></i> 组合加工
          </el-button>
        </div>
        
        <!-- 右侧搜索框 -->
        <div class="right-section">
          <el-form-item label="作业单号">
            <el-input 
              v-model="searchForm.jobCode" 
              placeholder="请输入作业单号" 
              clearable 
              class="search-input"
            />
          </el-form-item>
          <el-button type="primary" class="search-btn" @click="handleSearch">
            <i class="el-icon-search"></i> 查询
          </el-button>
          <el-button class="reset-btn" @click="resetSearch">
            <i class="el-icon-refresh"></i> 重置
          </el-button>
        </div>
      </el-form>
    </div>
    
    <!-- 作业列表表格 -->
    <el-table 
      :data="tableData" 
      v-loading="loading" 
      border 
      style="width: 100%; margin-top: 20px;"
      class="operations-table"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
    >
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="jobCode" label="作业单号" min-width="160" show-overflow-tooltip />
      <el-table-column label="作业类型" width="120" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.category === 1 ? 'warning' : 'success'" class="category-tag">
            {{ getCategoryLabel(scope.row.category) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'info' : scope.row.status === 2 ? 'success' : 'primary'" class="status-tag">
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作员工" width="120" align="center">
        <template #default="scope">
          <span class="employee-name">{{ getUserName(scope.row.empId) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" />
      
      <!-- 操作列 -->
      <el-table-column label="操作" width="220" fixed="right" align="center">
        <template #default="scope">
          <div class="action-buttons">
            <el-button 
              size="small" 
              class="action-btn view-btn"
              @click="handleViewDetails(scope.row.id)"
            >
              <i class="el-icon-view"></i> 查看
            </el-button>
            <el-button 
              size="small" 
              type="primary" 
              class="action-btn confirm-btn"
              :disabled="scope.row.status !== 1"
              @click="handleConfirm(scope.row.id)"
            >
              <i class="el-icon-check"></i> 确认
            </el-button>
            <el-button 
              size="small" 
              type="warning" 
              class="action-btn adjust-btn"
              :disabled="scope.row.status !== 2"
              @click="handleChange(scope.row.id)"
            >
              <i class="el-icon-edit"></i> 调整
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              class="action-btn delete-btn"
              :disabled="scope.row.status !== 1"
              @click="handleDelete(scope.row.id)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <el-pagination
      layout="total, sizes, prev, pager, next, jumper"
      :current-page="pagination.page"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      @size-change="(val) => { pagination.pageSize = val; handlePageChange(pagination.page); }"
      @current-change="handlePageChange"
      class="pagination-container"
    />
    
    <!-- 加工处理弹窗 -->
    <ProcessingDialog ref="processingDialogRef" @refresh="fetchOperationsList" />
  </div>
</template>

<style scoped>
.operations-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-bar {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7f4 100%);
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.search-form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.left-section {
  flex-shrink: 0;
  display: flex;
  gap: 12px;
}

.right-section {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  justify-content: flex-end;
  align-items: center;
  flex: 1;
}

/* 按钮样式 */
.action-btn {
  border-radius: 4px;
  transition: all 0.3s ease;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.search-input {
  width: 220px;
}

.search-btn {
  background-color: #409eff;
  border-color: #409eff;
}

.reset-btn {
  background-color: #f4f4f5;
  border-color: #dcdfe6;
  color: #606266;
}

.reset-btn:hover {
  background-color: #ecf5ff;
  border-color: #b3d8ff;
  color: #409eff;
}

/* 表格样式 */
.operations-table {
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
}

.operations-table :deep(.el-table__header th) {
  font-weight: 600;
}

.operations-table :deep(.el-table__row:hover) {
  background-color: #f5f9ff;
}

.category-tag, .status-tag {
  border-radius: 12px;
  padding: 0 12px;
}

.employee-name {
  font-weight: 500;
  color: #409eff;
}

/* 操作按钮组 */
.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: center;
}

.view-btn {
  background-color: #ecf5ff;
  border-color: #b3d8ff;
  color: #409eff;
}

.view-btn:hover {
  background-color: #409eff;
  border-color: #409eff;
  color: #fff;
}

.confirm-btn {
  background-color: #67c23a;
  border-color: #67c23a;
  color: #fff;
}

.confirm-btn:hover:not(:disabled) {
  background-color: #85ce61;
  border-color: #85ce61;
}

.adjust-btn {
  background-color: #e6a23c;
  border-color: #e6a23c;
  color: #fff;
}

.adjust-btn:hover:not(:disabled) {
  background-color: #ebb563;
  border-color: #ebb563;
}

.delete-btn {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: #fff;
}

.delete-btn:hover:not(:disabled) {
  background-color: #f78989;
  border-color: #f78989;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .left-section {
    justify-content: center;
  }
  
  .right-section {
    justify-content: center;
  }
  
  .action-buttons {
    flex-direction: column;
    align-items: center;
  }
  
  .operations-table {
    font-size: 12px;
  }
}

@media (max-width: 768px) {
  .operations-container {
    padding: 15px;
  }
  
  .search-bar {
    padding: 15px;
  }
  
  .search-input {
    width: 100%;
  }
  
  .el-table-column {
    padding: 5px 0;
  }
}
</style>